package com.qf.controller;

import com.qf.pojo.Cart;
import com.qf.pojo.User;
import com.qf.service.CartService;
import com.qf.service.impl.CartServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/cart")
public class CartController extends BaseServlet{
    
    public String create(HttpServletRequest request, HttpServletResponse response){
        //获取商品id
        String pid = request.getParameter("pid");
        //获取session会话中当前胡勇的用户id
        User user = (User)request.getSession().getAttribute("loginUser");
        if (user == null){
            return "redirect:/login.jsp";
        }

        //调用service层，将购物车存入数据库中
        CartService cartService = new CartServiceImpl();
        cartService.createCart(user.getId(), Integer.parseInt(pid));
        //跳转到购物车查询列表方法
        return "redirect:/cart?method=show";
    }

    /**
     * 查询指定用户的购物车数据，跳转到购物车列表页面展示
     * @return
     */
    public  String show(HttpServletRequest request, HttpServletResponse response){
        //获取session中用户id
        User user = (User)request.getSession().getAttribute("loginUser");
        if (user == null){
            return "redirect:/login.jsp";
        }
        //根据id调用service查询用户的购物车数据
        CartService cartService = new CartServiceImpl();
        List<Cart> cartList = cartService.findCartListByUid(user.getId());
        //将用户的购物车数据嵌入request中，带到页面中进行展示
        request.setAttribute("list", cartList);
        //跳转到购物车列表页面展示
        return "forward:/cart.jsp";
    }
    /**
     *  修改购物车中购物项的购买数量
     * @param request
     * @param response
     * @return
     */
    public String update(HttpServletRequest request, HttpServletResponse response){
        //从会话中获取当前登录用户id
        User loginUser =(User) request.getSession().getAttribute("loginUser");
        //获取购物项主键id
        String cid = request.getParameter("cid");
        //获取购物数量和单价
        String cnum = request.getParameter("cnum");
        String price = request.getParameter("price");
        //调用service  执行修改业务
        CartService cartService = new CartServiceImpl();
        cartService.updateCart(Integer.parseInt(cid), Integer.parseInt(cnum));
        //跳转到购物车列表方法
        return "redirect:/cart?method=show";
    }

    public String delete(HttpServletRequest request, HttpServletResponse response){
        //从session中获取当前登录用户对象
        User user =(User) request.getSession().getAttribute("loginUser");
        if(user == null){
            return "redirect:/loginjsp";
        }
        //获取购物项主键id
        String cid = request.getParameter("cid");
        //调用service根据购物项主键id删除
        CartService cartService = new CartServiceImpl();
        cartService.deleteById(Integer.parseInt(cid));
        //跳转到购物车查询列表页面，显示最新购物项数据
        return "redirect:/cart?method=show";
    }
}
